package io.kimmking.auth2.aspect;

import io.kimmking.auth2.unit.ResponseResultV1;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * 自定义/oauth/token接口返回的数据格式
 * 使用AOP切面增强/oauth/token接口
 */
@Aspect
@Component
@Slf4j
public class AuthTokenAspect {

    @Pointcut("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
    public void doing(){}

    @Around(value = "doing()")
    public Object handleAuthToken(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

        Object[] args = proceedingJoinPoint.getArgs();
        log.info("切点入参: " + Arrays.toString(args));

        Object result = proceedingJoinPoint.proceed();
        log.info("开始返回/oauth/token的结果");
        ResponseEntity<OAuth2AccessToken> responseEntity = (ResponseEntity<OAuth2AccessToken>) result;
        OAuth2AccessToken body = responseEntity.getBody();
        return ResponseEntity
                .status(HttpStatus.OK)
                .body(ResponseResultV1.succeed(body,"successfully done!"));
    }

}
